#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    long long minimumTotalDistance(vector<int>& robot, vector<vector<int>>& factory) {
        int n = robot.size(), m = factory.size();
        sort(robot.begin(), robot.end());
        sort(factory.begin(), factory.end());
        vector<vector<long long>> dp(m + 1, vector<long long>(n + 1, 1e13));
        for (int i = 0; i <= m; i++) dp[i][0] = 0;
        for (int i = 1; i <= m; i++)
            for (int j = 1; j <= n; j++) {
                dp[i][j] = dp[i - 1][j];
                long long sum = 0;
                for (int k = 1; k <= min(j, factory[i - 1][1]); k++) {
                    sum += abs(factory[i - 1][0] - robot[j - k]);
                    dp[i][j] = min(dp[i][j], dp[i - 1][j - k] + sum);
                    //cout << i - 1 << ":" << j - k << " " << dp[i - 1][j - k] << ' ' << sum << ' ' << dp[i][j] << endl;
                }
            }
        // for(int i = 0; i <= m; i++) {
        //     for(int j = 0; j <= n; j++) cout << dp[i][j] << ' ';
        //     cout << endl;
        // }
        return dp[m][n];
    }
};